package com.example.controller;

import com.example.entity.RestBean;
import com.example.service.ImageService;
import com.example.utils.Const;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import static com.example.utils.Const.USER_ID;

@Slf4j
@RestController
@RequestMapping("/api/image")
public class ImageController {

    @Resource
    private ImageService imageService;


    /**
     * 用户上传头像
     * @param multipartFile 图片文件
     * @param id 用户Id
     * @return 随机生成UUID，构成的URL
     */
    @PostMapping("/avatar")
    public RestBean<String> uploadAvatar(@RequestParam("file") MultipartFile multipartFile,
                                         @RequestAttribute(USER_ID) int id) throws Exception{
        if(multipartFile.getSize() > 1024 * 100)
            return RestBean.failure(400,"图像图片不能大于100Kb");
        log.info("正在上传头像...");
        String url = imageService.uploadAvatar(multipartFile, id);
        if(url != null){
            return RestBean.success(url);
        }else {
            return RestBean.failure(400,"头像上传失败，请联系管理员");
        }
    }

    /**
     * 图片缓存（minio）
     * @param file 图片
     * @param id 用户Id
     * @return url
     */
    @PostMapping("/cache")
    public RestBean<String> uploadImage(@RequestParam("file") MultipartFile file,
                                        @RequestAttribute(USER_ID) int id,
                                        HttpServletResponse response) throws IOException {
        if(file.getSize() > 1024 * 1024 * 5)
            return RestBean.failure(400, "头像图片不能大于5MB");
        log.info("正在进行图片上传操作...");
        String url = imageService.uploadImage(file, id);
        if(url != null) {
            log.info("图片上传成功，大小: " + file.getSize());
            return RestBean.success(url);
        } else {
            response.setStatus(400);
            return RestBean.failure(400, "图片上传失败，请联系管理员！");
        }
    }


}
